'use strict';

import { winelistModel } from "../model/winelist";
import { ServiceBase, Exceptions } from '../kalend';
import _ = require("underscore");
import { merchantService } from "./merchant";

class WinelistService extends ServiceBase {
    constructor() {
        super(winelistModel)
    }
    async query(params: any) {
        const offset = params.offset;
        const limit = params.limit;
        const name = params.name;
        const status = params.status;
        const type = params.type;

        let filter: any = {};
        if (name) {
            filter.winename = { $regex: name, $options: 'i' };
        }

        if (status === 1 || status === 0) {
            filter.status = status;
        }
        if (type === 1 || type === 2) {
            filter.type = [type];
        }

        let data: any = await this.queryPagination(offset, limit, {
            filter: filter,
            sort: { order: 1 }
        });
        data.rows = data.rows.map((a: any) => {
            if (a.type) {
                if ((a.type as Array<any>).findIndex((b) => {
                    return b == 1;
                }) >= 0) {
                    a.typename = '酒';
                } else {
                    a.typename = '饮料';
                }
            }
            return a;
        })
        return data;
    }
    async save(doc: any) {
        if (doc._id) {
            return this.update(doc._id, doc);
        } else {
            let da = await this.create(doc);
            merchantService.addwine(da._id);
            return da;
        }
    }
    async queryalls() {
        return this.queryAll({
            filter: { status: 1 }
        });
    }

}

export const winelistService = new WinelistService();